package com.bootcamp.s2_0922.ds.Exercise._0930_Ex;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @program: myClassCode
 * @description: if words' letters are fully contained in chars, then it is a good word.
 * @author: Keyu Li
 * @create: 2021-09-30 19:43
 **/

public class Ex2_GoodWords {
    public static void main(String[] args) {
        String[] words = {"cat", "bt", "hat", "tree"};
        String chars = "atach";


        int count = 0;
        for (int i = 0; i < words.length; i++) {
            // 假设字符串全部由小写字母组成
            count += judgeGoodWord(words[i], chars);
            // 如果字符串是由任意字符组成的
            // 使用 List 的 containsAll 方法
            //count += judgeByListAPI(words[i], chars);
        }
        System.out.println(count);

    }

    private static int judgeByListAPI(String word, String chars) {
        List<Character> wl = new ArrayList<>(word.length());
        List<Character> cl = new ArrayList<>(chars.length());
        for (int i = 0; i < word.length(); i++) {
            wl.add(word.charAt(i));
        }
        for (int i = 0; i < chars.length(); i++) {
            cl.add(chars.charAt(i));
        }
        if (cl.containsAll(wl)) return word.length();
        return 0;
    }

    public static int judgeGoodWord(String word, String chars) {
        // 定义一个 a-z 数组存放每个字母
        int[] letterCount = new int[26];
        // 将 chars 按照字母下标存档到该数组
        for (int i = 0; i < chars.length(); i++) {
            char temp = chars.charAt(i);
            letterCount[temp - 'a']++;
        }
        // 遍历 word
        for (int i = 0; i < word.length(); i++) {
            char temp = word.charAt(i);
            if (letterCount[temp - 'a'] == 0)
                return 0;
            letterCount[temp - 'a']--;
        }
        return word.length();
    }
}
